﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Electric;
using YArchitech.LIB;
using YArchitech.MEP.Electric.Common;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Office.Interop.Excel;

namespace YArchitech.MEP.Electric.CableLay
{
	public partial class CableLayMainForm : System.Windows.Forms.Form
	{
		public CableLayMainForm(UIDocument uiDoc, ExternalEvent exEvent, RequestHandler handler)
		{
			this.InitializeComponent();
			this.m_uiDoc = uiDoc;
			this.m_doc = uiDoc.ActiveView.Document;
			this.m_Handler = handler;
			this.m_ExEvent = exEvent;
		}

		private void CableLayMainForm_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
			this.Text = string.Format("{0} - 【{1}】", "电缆敷设", "请新建或打开一个工程");
			this.InitToolbar();
			this.progressBar.Visible = false;
			string projectFile = this.ReadProjectFilePath();
			if (!this.OpenProject(projectFile))
			{
				this.labelDescription.Text = "请新建或打开一个工程";
			}
		}

		private void InitToolbar()
		{
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonNew", "新建", "新建工程", YArchitech.Electric.Resources.GetImage("New16"), new EventHandler(this.ToolStripItem_New_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonOpen", "打开", "打开工程", YArchitech.Electric.Resources.GetImage("Open16"), new EventHandler(this.ToolStripItem_Open_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonSave", "保存", "保存工程", YArchitech.Electric.Resources.GetImage("Save16"), new EventHandler(this.ToolStripItem_Save_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonImport", "导入", "导入电缆清册", YArchitech.Electric.Resources.GetImage("ExcelLoad16"), new EventHandler(this.ToolStripItem_Import_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonBackFill", "回填", "敷设结果回填到原Excel", YArchitech.Electric.Resources.GetImage("ReBackExcel16"), new EventHandler(this.ToolStripItem_BackFill_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonExport", "导出", "导出到新Excel文件", YArchitech.Electric.Resources.GetImage("Excel16"), new EventHandler(this.ToolStripItem_Export_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonFilter", "过滤", "按条件过滤电缆清册数据", YArchitech.Electric.Resources.GetImage("Filter16"), new EventHandler(this.ToolStripItem_Filter_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonReShow", "显示全部", "显示全部电缆清册数据", YArchitech.Electric.Resources.GetImage("Visible16"), new EventHandler(this.ToolStripItem_ReShow_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonLayRule", "敷设规则", "设置敷设规则", YArchitech.Electric.Resources.GetImage("LayRule16"), new EventHandler(this.ToolStripItem_LayRule_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonAutoLaying", "自动敷设", "按敷设规则搜索最短路径自动进行敷设", YArchitech.Electric.Resources.GetImage("AutoLaying16"), new EventHandler(this.ToolStripItem_AutoLaying_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonLayingPath", "查看路径", "三维视图下查看敷设路径", YArchitech.Electric.Resources.GetImage("LayPath16"), new EventHandler(this.ToolStripItem_LayingPath_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonRemove", "清除", "清除敷设信息", YArchitech.Electric.Resources.GetImage("Clear16"), new EventHandler(this.ToolStripItem_Remove_Click)));
			this.toolStripMain.Items.Add(this.NewToolStripItem("buttonRemoveAll", "清除全部", "清除所有敷设信息", YArchitech.Electric.Resources.GetImage("ClearAll16"), new EventHandler(this.ToolStripItem_RemoveAll_Click)));
		}

		private ToolStripButton NewToolStripItem(string name, string text, string tipText, Image image, EventHandler onClick)
		{
			return new ToolStripButton(text, image, onClick, name)
			{
				DisplayStyle = ToolStripItemDisplayStyle.ImageAndText,
				TextImageRelation = TextImageRelation.ImageBeforeText,
				ToolTipText = tipText
			};
		}

		private void ToolStripItem_New_Click(object sender, EventArgs e)
		{
			NewProjectForm newProjectForm = new NewProjectForm();
			if (newProjectForm.ShowDialog() != DialogResult.OK)
			{
				return;
			}
			string projectFile = newProjectForm.ProjectFile;
			string projectDescription = newProjectForm.ProjectDescription;
			this.m_FieldList = newProjectForm.HeaderFields;
			this.SaveData();
			CableLayDatabase.ThisDb.SetDataSource(projectFile);
			CableLayDatabase.ThisDb.SaveProjectDescribe(projectDescription);
			CableLayDatabase.ThisDb.SaveProjectFields(this.m_FieldList);
			this.InitGridColumnHeader();
			this.SaveProjectFilePath(projectFile);
			this.Text = string.Format("{0} - 【{1}】", "电缆敷设", projectFile);
			this.labelDescription.Text = "就绪";
		}

		private void ToolStripItem_Open_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "电缆敷设工程文件(*.hdb)|*.hdb";
			if (openFileDialog.ShowDialog(this) != DialogResult.OK)
			{
				return;
			}
			string fileName = openFileDialog.FileName;
			if (!this.OpenProject(fileName))
			{
				this.labelDescription.Text = "请新建或打开一个工程";
				return;
			}
			this.SaveProjectFilePath(fileName);
		}

		private void ToolStripItem_Save_Click(object sender, EventArgs e)
		{
			if (!this.IsReady() || !this.m_isEdited)
			{
				return;
			}
			this.m_isEdited = false;
			this.dataGridView.EndEdit();
			List<CableListData> list = new List<CableListData>();
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = dataGridViewRow.Tag as CableListData;
					if (cableListData != null && cableListData.IsValid())
					{
						list.Add(cableListData);
					}
				}
			}
			CableLayDatabase.ThisDb.SaveCableListDatas(list);
		}

		private void ToolStripItem_Import_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			CableListImportForm cableListImportForm = new CableListImportForm(this.m_FieldList);
			if (cableListImportForm.ShowDialog() != DialogResult.OK)
			{
				return;
			}
			if (cableListImportForm.m_cableListData == null || cableListImportForm.m_cableListData.Count <= 0)
			{
				return;
			}
			this.AddCableListDatas(cableListImportForm.m_cableListData, cableListImportForm.m_addDataMode);
			this.labelDescription.Text = "导入电缆清册完成。就绪";
			this.m_isEdited = true;
			MessageBox.Show("导入电缆清册数据完成！", "盈建科提示", MessageBoxButtons.OK);
		}

		private void ToolStripItem_BackFill_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			List<CableListData> list = new List<CableListData>();
			if (this.dataGridView.SelectedRows.Count <= 0)
			{
				IEnumerator enumerator = ((IEnumerable)this.dataGridView.Rows).GetEnumerator();
				{
					while (enumerator.MoveNext())
					{
						object obj = enumerator.Current;
						DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
						if (dataGridViewRow.Tag != null)
						{
							CableListData item = (CableListData)dataGridViewRow.Tag;
							list.Add(item);
						}
					}
					goto IL_E3;
				}
			}
			foreach (object obj2 in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow2 = (DataGridViewRow)obj2;
				if (dataGridViewRow2.Tag != null)
				{
					CableListData item2 = (CableListData)dataGridViewRow2.Tag;
					list.Add(item2);
				}
			}
			IL_E3:
			if (list.Count <= 0)
			{
				MessageBox.Show("没有可供回填的数据，请检查。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			if (CableLayDatabase.ThisDb.BackfillCableDatasToExcel(list))
			{
				this.labelDescription.Text = "回填敷设结果完成。就绪";
				MessageBox.Show("回填敷设结果完成！", "盈建科提示", MessageBoxButtons.OK);
			}
		}

		private void ToolStripItem_Export_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			List<CableListData> list = new List<CableListData>();
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData item = (CableListData)dataGridViewRow.Tag;
					list.Add(item);
				}
			}
			if (list.Count <= 0)
			{
				MessageBox.Show("没有可供导出的数据，请检查。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			CableListExportForm cableListExportForm = new CableListExportForm(this);
			if (DialogResult.OK == cableListExportForm.ShowDialog())
			{
				this.ExportExcel(cableListExportForm);
			}
		}

		private void ExportExcel(CableListExportForm dlg)
		{
			Microsoft.Office.Interop.Excel.Application application = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046")));
			application.Visible = true;
			Workbook workbook = application.Workbooks.Add(Missing.Value);
            //if (CableLayMainForm.<>o__31.<>p__0 == null)
            //{
            //    CableLayMainForm.<>o__31.<>p__0 = CallSite<Func<CallSite, object, Worksheet>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(Worksheet), typeof(CableLayMainForm)));
            //}
            //Worksheet worksheet = CableLayMainForm.<>o__31.<>p__0.Target(CableLayMainForm.<>o__31.<>p__0, workbook.ActiveSheet);
            //if (!dlg.m_paging)
            //{
            //    for (int i = 0; i < this.dataGridView.ColumnCount; i++)
            //    {
            //        if (this.dataGridView.Columns[i].Visible)
            //        {
            //            worksheet.Cells[1, i + 1] = this.dataGridView.Columns[i].HeaderText.Trim();
            //            if (CableLayMainForm.<>o__31.<>p__1 == null)
            //            {
            //                CableLayMainForm.<>o__31.<>p__1 = CallSite<Func<CallSite, object, Range>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(Range), typeof(CableLayMainForm)));
            //            }
            //            CableLayMainForm.<>o__31.<>p__1.Target(CableLayMainForm.<>o__31.<>p__1, worksheet.Columns[i + 1, Type.Missing]).ColumnWidth = 15;
            //        }
            //    }
            //    worksheet.get_Range("A1", "H1").HorizontalAlignment = XlHAlign.xlHAlignCenter;
            //    for (int j = 0; j < this.dataGridView.Rows.Count; j++)
            //    {
            //        for (int k = 0; k < this.dataGridView.ColumnCount; k++)
            //        {
            //            if (CableLayMainForm.<>o__31.<>p__2 == null)
            //            {
            //                CableLayMainForm.<>o__31.<>p__2 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.SetMember(CSharpBinderFlags.None, "NumberFormatLocal", typeof(CableLayMainForm), new CSharpArgumentInfo[]
            //                {
            //                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
            //                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null)
            //                }));
            //            }
            //            CableLayMainForm.<>o__31.<>p__2.Target(CableLayMainForm.<>o__31.<>p__2, worksheet.Cells[j + 2, k + 1], "@");
            //            worksheet.Cells[j + 2, k + 1] = this.dataGridView.Rows[j].Cells[k].Value.ToString();
            //        }
            //    }
            //    return;
            //}
			int num = 0;
			for (int l = 0; l < this.dataGridView.Rows.Count; l++)
			{
				int num2 = l % dlg.m_rowCount;
				if (num2 == 0)
				{
					num++;
					if (num > 1)
					{
                        //if (CableLayMainForm.<>o__31.<>p__3 == null)
                        //{
                        //    CableLayMainForm.<>o__31.<>p__3 = CallSite<Func<CallSite, object, Worksheet>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(Worksheet), typeof(CableLayMainForm)));
                        //}
                        //worksheet = CableLayMainForm.<>o__31.<>p__3.Target(CableLayMainForm.<>o__31.<>p__3, workbook.Worksheets.Add(Type.Missing, worksheet, Type.Missing, Type.Missing));
					}
					for (int m = 0; m < this.dataGridView.ColumnCount; m++)
					{
						if (this.dataGridView.Columns[m].Visible)
						{
                            //worksheet.Cells[1, m + 1] = this.dataGridView.Columns[m].HeaderText.Trim();
                            //if (CableLayMainForm.<>o__31.<>p__4 == null)
                            //{
                            //    CableLayMainForm.<>o__31.<>p__4 = CallSite<Func<CallSite, object, Range>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(Range), typeof(CableLayMainForm)));
                            //}
                            //CableLayMainForm.<>o__31.<>p__4.Target(CableLayMainForm.<>o__31.<>p__4, worksheet.Columns[m + 1, Type.Missing]).ColumnWidth = 15;
						}
					}
                    //worksheet.get_Range("A1", "H1").HorizontalAlignment = XlHAlign.xlHAlignCenter;
				}
				for (int n = 0; n < this.dataGridView.ColumnCount; n++)
				{
                    //if (CableLayMainForm.<>o__31.<>p__5 == null)
                    //{
                    //    CableLayMainForm.<>o__31.<>p__5 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.SetMember(CSharpBinderFlags.None, "NumberFormatLocal", typeof(CableLayMainForm), new CSharpArgumentInfo[]
                    //    {
                    //        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                    //        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null)
                    //    }));
                    //}
                    //CableLayMainForm.<>o__31.<>p__5.Target(CableLayMainForm.<>o__31.<>p__5, worksheet.Cells[num2 + 2, n + 1], "@");
                    //worksheet.Cells[num2 + 2, n + 1] = this.dataGridView.Rows[l].Cells[n].Value.ToString();
				}
			}
		}

		private void ToolStripItem_Filter_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			List<CableListField> list = new List<CableListField>();
			foreach (CableListField cableListField in this.m_FieldList)
			{
				if (cableListField.IsForQuery)
				{
					list.Add(cableListField);
				}
			}
			if (list.Count <= 0)
			{
				MessageBox.Show("没有用作查询的字段。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			CableListFilterForm cableListFilterForm = new CableListFilterForm(list);
			if (cableListFilterForm.ShowDialog() != DialogResult.OK)
			{
				return;
			}
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData data = (CableListData)dataGridViewRow.Tag;
					dataGridViewRow.Visible = (this.IsSatisfyAndFilter(data, cableListFilterForm.FilterItems) || this.IsSatisfyOrFilter(data, cableListFilterForm.FilterItems));
				}
			}
			this.labelDescription.Text = "过滤完成。就绪";
		}

		private void ToolStripItem_ReShow_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				((DataGridViewRow)obj).Visible = true;
			}
		}

		private void ToolStripItem_LayRule_Click(object sender, EventArgs e)
		{
			new CableLayRuleForm().ShowDialog();
		}

		private void ToolStripItem_AutoLaying_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			List<CableListData> list = new List<CableListData>();
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = (CableListData)dataGridViewRow.Tag;
					if (!string.IsNullOrWhiteSpace(cableListData.CableNum) && !string.IsNullOrWhiteSpace(cableListData.StartNum) && !string.IsNullOrWhiteSpace(cableListData.EndNum))
					{
						list.Add(cableListData);
					}
				}
			}
			if (list.Count <= 0)
			{
				MessageBox.Show("没有数据行被选中，请先选择。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			YArchitech.MEP.Electric.CableLay.Application.thisApp.ResetCableListData(list);
			this.m_Handler.Request.Make(RequestId.CableLaying);
			this.m_ExEvent.Raise();
		}

		public void UpdateDataAfterAutoLaying()
		{
			if (this.dataGridView.SelectedRows.Count == 0)
			{
				return;
			}
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow row = (DataGridViewRow)obj;
				this.UpdateRowData(row, true);
			}
			this.labelDescription.Text = "敷设完成。就绪";
			this.m_isEdited = true;
		}

		private void ToolStripItem_LayingPath_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			if (this.dataGridView.SelectedRows.Count == 0 || this.dataGridView.SelectedRows.Count > 1)
			{
				MessageBox.Show("请先选择数据行且只选中一行。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			DataGridViewRow dataGridViewRow = this.dataGridView.SelectedRows[0];
			if (dataGridViewRow.Tag == null)
			{
				MessageBox.Show("该数据行还未进行敷设。请先敷设，再查看路径。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			CableListData cableListData = (CableListData)dataGridViewRow.Tag;
			if (string.IsNullOrEmpty(cableListData.Length) || string.IsNullOrEmpty(cableListData.LayPath) || string.IsNullOrEmpty(cableListData.LayPathIDs))
			{
				MessageBox.Show("该数据行还未进行敷设。请先敷设，再查看路径。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			YArchitech.MEP.Electric.CableLay.Application.thisApp.ResetCableListData(cableListData);
			this.m_Handler.Request.Make(RequestId.LookUpLayPath);
			this.m_ExEvent.Raise();
		}

		private void ToolStripItem_Remove_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			if (this.dataGridView.SelectedRows.Count == 0)
			{
				MessageBox.Show("没有数据行被选中，请先选择。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			List<CableListData> list = new List<CableListData>();
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = (CableListData)dataGridViewRow.Tag;
					if (!string.IsNullOrEmpty(cableListData.Length) && !string.IsNullOrEmpty(cableListData.LayPath))
					{
						list.Add(cableListData);
					}
				}
			}
			if (list.Count <= 0)
			{
				MessageBox.Show("没有任何敷设过的数据行被选中，请重新选择。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				return;
			}
			YArchitech.MEP.Electric.CableLay.Application.thisApp.ResetCableListData(list);
			this.m_Handler.Request.Make(RequestId.RemoveLayCable);
			this.m_ExEvent.Raise();
		}

		public void UpdateDataAfterRemove()
		{
			if (this.dataGridView.SelectedRows.Count == 0)
			{
				return;
			}
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = (CableListData)dataGridViewRow.Tag;
					if (cableListData != null && !string.IsNullOrEmpty(cableListData.Length) && !string.IsNullOrEmpty(cableListData.LayPath))
					{
						cableListData.Length = string.Empty;
						cableListData.LayPath = string.Empty;
						cableListData.Remark = string.Empty;
						this.UpdateRowData(dataGridViewRow, true);
					}
				}
			}
			this.labelDescription.Text = "清除选中行的敷设信息完成。就绪";
			this.m_isEdited = true;
		}

		private void ToolStripItem_RemoveAll_Click(object sender, EventArgs e)
		{
			if (!this.IsReady())
			{
				return;
			}
			this.dataGridView.EndEdit();
			this.m_Handler.Request.Make(RequestId.RemoveAllLayCable);
			this.m_ExEvent.Raise();
		}

		public void UpdateDataAfterRemoveAll()
		{
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = (CableListData)dataGridViewRow.Tag;
					if (cableListData != null)
					{
						cableListData.Length = string.Empty;
						cableListData.LayPath = string.Empty;
						cableListData.Remark = string.Empty;
						this.UpdateRowData(dataGridViewRow, true);
					}
				}
			}
			this.labelDescription.Text = "清除敷设信息完成。就绪";
			this.m_isEdited = true;
		}

		private void CableLayMainForm_Resize(object sender, EventArgs e)
		{
			if (this.m_GridWidth == this.dataGridView.Width)
			{
				return;
			}
			this.labelDescription.Width = this.statusStrip.Width - 180;
			this.ResizeGridColumnWidth();
		}

		private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
		{
			if (e.RowIndex < 0 || e.RowIndex >= this.dataGridView.Rows.Count || e.ColumnIndex < 0 || e.ColumnIndex >= this.dataGridView.ColumnCount)
			{
				e.Cancel = true;
				return;
			}
			object value = this.dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
			this.m_lastValue = ((value == null) ? string.Empty : Convert.ToString(value));
		}

		private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0 || e.RowIndex >= this.dataGridView.Rows.Count || e.ColumnIndex < 0 || e.ColumnIndex >= this.dataGridView.ColumnCount)
			{
				return;
			}
			object value = this.dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
			if (((value == null) ? string.Empty : Convert.ToString(value)) == this.m_lastValue)
			{
				return;
			}
			this.UpdateRowData(this.dataGridView.Rows[e.RowIndex], false);
			this.m_isEdited = true;
		}

		private void dataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
		{
			this.m_showContextMenu = false;
			if (e.Button != MouseButtons.Right || e.RowIndex >= this.dataGridView.RowCount)
			{
				return;
			}
			if (this.dataGridView.SelectedRows.Count <= 0)
			{
				return;
			}
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (e.RowIndex == dataGridViewRow.Index)
				{
					this.m_showContextMenu = true;
					break;
				}
			}
		}

		private void dataGridView_MouseUp(object sender, MouseEventArgs e)
		{
			if (this.m_showContextMenu)
			{
				this.contextMenu.Show(this.dataGridView, e.Location);
				this.m_showContextMenu = false;
			}
		}

		private void cmdDelete_Click(object sender, EventArgs e)
		{
			if (this.dataGridView.SelectedRows.Count <= 0)
			{
				return;
			}
			int index = this.dataGridView.SelectedRows[0].Index;
			foreach (object obj in this.dataGridView.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				this.dataGridView.Rows.Remove(dataGridViewRow);
			}
			this.m_isEdited = true;
			if (this.dataGridView.Rows.Count <= 0)
			{
				return;
			}
			this.dataGridView.ClearSelection();
			if (index >= this.dataGridView.Rows.Count)
			{
				this.dataGridView.Rows[0].Selected = true;
				return;
			}
			this.dataGridView.Rows[index].Selected = true;
		}

		private void dataGridView_KeyDown(object sender, KeyEventArgs e)
		{
			try
			{
				Keys keyCode = e.KeyCode;
				if (keyCode == Keys.Delete)
				{
					this.cmdDelete_Click(null, null);
					e.SuppressKeyPress = true;
				}
			}
			catch (Exception)
			{
			}
		}

		private void CableLayMainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.SaveData();
		}

		private bool IsReady()
		{
			if (this.dataGridView.Columns.Count <= 0 || string.IsNullOrWhiteSpace(CableLayDatabase.ThisDb.GetDataSource()) || !CableLayDatabase.ThisDb.IsOpening())
			{
				MessageBox.Show("请先新建或打开一个工程后再进行此操作。", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				this.labelDescription.Text = "请新建或打开一个工程";
				return false;
			}
			this.labelDescription.Text = "就绪";
			return true;
		}

		private bool IsReadyNoPrompt()
		{
			return this.dataGridView.Columns.Count > 0 && !string.IsNullOrWhiteSpace(CableLayDatabase.ThisDb.GetDataSource()) && CableLayDatabase.ThisDb.IsOpening();
		}

		private void InitGridColumnHeader()
		{
			this.dataGridView.Columns.Clear();
			foreach (CableListField cableListField in this.m_FieldList)
			{
				DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
				dataGridViewTextBoxColumn.Name = cableListField.DbName;
				if (string.IsNullOrWhiteSpace(cableListField.Title))
				{
					dataGridViewTextBoxColumn.HeaderText = cableListField.Name;
				}
				else
				{
					dataGridViewTextBoxColumn.HeaderText = cableListField.Title;
				}
				dataGridViewTextBoxColumn.Tag = cableListField;
				this.dataGridView.Columns.Add(dataGridViewTextBoxColumn);
			}
			DataGridViewColumn dataGridViewColumn = this.dataGridView.Columns["Length"];
			dataGridViewColumn.ReadOnly = true;
            dataGridViewColumn.DefaultCellStyle.BackColor = System.Drawing.Color.Wheat;
			DataGridViewColumn dataGridViewColumn2 = this.dataGridView.Columns["LayPath"];
			dataGridViewColumn2.ReadOnly = true;
            dataGridViewColumn2.DefaultCellStyle.BackColor = System.Drawing.Color.Wheat;
			this.ResizeGridColumnWidth();
		}

		private void ResizeGridColumnWidth()
		{
			this.m_GridWidth = this.dataGridView.Width;
			int num = this.m_GridWidth - 20;
			int count = this.dataGridView.Columns.Count;
			double num2 = 1.0 / (double)count;
			int num3 = 0;
			foreach (object obj in this.dataGridView.Columns)
			{
				DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)obj;
				if (dataGridViewColumn.Index == count - 1)
				{
					dataGridViewColumn.Width = num - num3 - 2;
				}
				else
				{
					dataGridViewColumn.Width = Convert.ToInt32((double)num * num2);
				}
				num3 += dataGridViewColumn.Width;
			}
		}

		private void AddCableListDatas(List<CableListData> dataList, AddDataMode mode)
		{
			if (dataList == null || dataList.Count <= 0)
			{
				return;
			}
			foreach (CableListData cableListData in dataList)
			{
				switch (mode)
				{
				case AddDataMode.Add_Ignore:
					this.AddNewRow(cableListData);
					break;
				case AddDataMode.Add_Overwrite:
				{
					DataGridViewRow dataGridViewRow = this.FindDataRow(cableListData);
					if (dataGridViewRow == null)
					{
						this.AddNewRow(cableListData);
					}
					else if (cableListData.IsValid())
					{
						dataGridViewRow.Tag = cableListData;
						this.UpdateRowData(dataGridViewRow, true);
					}
					break;
				}
				case AddDataMode.Add_SameRetain:
					if (this.FindDataRow(cableListData) == null)
					{
						this.AddNewRow(cableListData);
					}
					break;
				default:
					return;
				}
			}
		}

		private void AddNewRow(CableListData data)
		{
			if (data == null || !data.IsValid())
			{
				return;
			}
			DataGridViewRow dataGridViewRow = new DataGridViewRow();
			int index = this.dataGridView.Rows.Add(dataGridViewRow);
			dataGridViewRow = this.dataGridView.Rows[index];
			dataGridViewRow.Tag = data;
			this.UpdateRowData(dataGridViewRow, true);
		}

		private void UpdateRowData(DataGridViewRow row, bool showOrSave)
		{
			if (row == null || row.Tag == null)
			{
				return;
			}
			CableListData cableListData = row.Tag as CableListData;
			foreach (object obj in this.dataGridView.Columns)
			{
				DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)obj;
				if (showOrSave)
				{
					row.Cells[dataGridViewColumn.Name].Value = cableListData[dataGridViewColumn.Name];
				}
				else
				{
					cableListData[dataGridViewColumn.Name] = row.Cells[dataGridViewColumn.Name].Value;
				}
			}
		}

		private DataGridViewRow FindDataRow(CableListData data)
		{
			if (data == null || string.IsNullOrWhiteSpace(data.CableNum))
			{
				return null;
			}
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData obj2 = (CableListData)dataGridViewRow.Tag;
					if (data.Equals(obj2))
					{
						return dataGridViewRow;
					}
				}
			}
			return null;
		}

		private string ReadProjectFilePath()
		{
			YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(CableLayCommon.GetUserDataFile(), "ElectricData");
			xmlHelper.SelectNode("CableLayProject");
			return xmlHelper.GetAttributeEx("ProjectPath", string.Empty);
		}

		private void SaveProjectFilePath(string projectPath)
		{
			YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(CableLayCommon.GetUserDataFile(), "ElectricData");
			xmlHelper.SelectNode("CableLayProject");
			xmlHelper.SetAttribute("ProjectPath", projectPath);
			xmlHelper.SaveXml("");
		}

		private bool OpenProject(string projectFile)
		{
			if (string.IsNullOrWhiteSpace(projectFile) || !File.Exists(projectFile))
			{
				return false;
			}
			this.SaveData();
			CableLayDatabase.ThisDb.SetDataSource(projectFile);
			this.m_FieldList = CableLayDatabase.ThisDb.GetProjectFields();
			this.InitGridColumnHeader();
			List<CableListData> cableListDatas = CableLayDatabase.ThisDb.GetCableListDatas();
			this.AddCableListDatas(cableListDatas, AddDataMode.Add_Ignore);
			this.Text = string.Format("{0} - 【{1}】", "电缆敷设", projectFile);
			this.labelDescription.Text = "就绪";
			return true;
		}

		private void SaveData()
		{
			if (!this.IsReadyNoPrompt() || !this.m_isEdited)
			{
				return;
			}
			if (MessageBox.Show("清册数据已有更改，是否保存？", "盈建科提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) != DialogResult.Yes)
			{
				return;
			}
			this.m_isEdited = false;
			this.dataGridView.EndEdit();
			List<CableListData> list = new List<CableListData>();
			foreach (object obj in ((IEnumerable)this.dataGridView.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Tag != null)
				{
					CableListData cableListData = dataGridViewRow.Tag as CableListData;
					if (cableListData != null && cableListData.IsValid())
					{
						list.Add(cableListData);
					}
				}
			}
			CableLayDatabase.ThisDb.SaveCableListDatas(list);
		}

		private bool IsSatisfyAndFilter(CableListData data, List<FilterItem> filterItems)
		{
			if (data == null)
			{
				return false;
			}
			if (filterItems == null || filterItems.Count <= 0)
			{
				return true;
			}
			bool flag = false;
			foreach (FilterItem filterItem in filterItems)
			{
				if (RelationOperator.Or != filterItem.Relation)
				{
					flag = ((filterItem.Compare == CompareOperator.Equal) ? data.IsMatch(filterItem.Field.DbName, filterItem.Value) : data.IsContains(filterItem.Field.DbName, filterItem.Value));
					if (!flag)
					{
						return false;
					}
				}
			}
			return flag;
		}

		private bool IsSatisfyOrFilter(CableListData data, List<FilterItem> filterItems)
		{
			if (data == null)
			{
				return false;
			}
			if (filterItems == null || filterItems.Count <= 0)
			{
				return true;
			}
			foreach (FilterItem filterItem in filterItems)
			{
				if (filterItem.Relation != RelationOperator.And && ((filterItem.Compare == CompareOperator.Equal) ? data.IsMatch(filterItem.Field.DbName, filterItem.Value) : data.IsContains(filterItem.Field.DbName, filterItem.Value)))
				{
					return true;
				}
			}
			return false;
		}

		private static char[] m_sp = new char[]
		{
			','
		};

		private const string Form_Title = "电缆敷设";

		private const string Prompt_Text_Project = "请新建或打开一个工程";

		private const string Prompt_Text_Ready = "就绪";

		private const string Prompt_Text_Import = "导入电缆清册完成。就绪";

		private const string Prompt_Text_BackFill = "回填敷设结果完成。就绪";

		private const string Prompt_Text_Filter = "过滤完成。就绪";

		private const string Prompt_Text_Remove = "清除选中行的敷设信息完成。就绪";

		private const string Prompt_Text_RemoveAll = "清除敷设信息完成。就绪";

		private const string Prompt_Text_AutoLaying = "敷设完成。就绪";

		private const string Xml_Node_Root = "CableLayProject";

		private const string Xml_Att_ProjectPath = "ProjectPath";

		private int m_GridWidth = 1080;

		private List<CableListField> m_FieldList = new List<CableListField>();

		private UIDocument m_uiDoc;

		private Document m_doc;

		private string m_lastValue = string.Empty;

		private bool m_isEdited;

		private bool m_showContextMenu;

		private RequestHandler m_Handler;

		private ExternalEvent m_ExEvent;
	}
}
